package com.mars.algorithm;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author King
 * @create 2020/6/22 14:12
 */
public class TheSumOfTwoNumbers {

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 17;
        int[] tmp = twoSum2(nums, target);
        System.out.println("sfgdgh");
    }

    public static int[] twoSum(int[] nums, int target) {

        int[] result = new int[2];
        if (nums.length < 2) {
            return result;
        }
        for (int i = 0; i < nums.length; i++) {
            int tmp = i;
            for (int j = tmp + 1; j < nums.length; j++) {
                int t = j;
                if (nums[tmp] + nums[t] == target) {
                    result[0] = tmp;
                    result[1] = t;
                    return result;
                }
            }
        }
        return result;
    }


    public static int[] twoSum2(int[] nums, int target) {

        int[] result = new int[2];
        if (nums.length < 2) {
            return result;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int res = target - nums[i];
            if (map.containsKey(res)) {
                return new int[]{map.get(res), i};
            }
            map.put(nums[i], i);
        }
        return result;
    }
}
